package com.lg.spring.ioc;

import com.lg.spring.ioc.common.UserRepository;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 通过 依赖注入 的方式实现 注入bean，实现控制反转ioc
 *
 * 通过类型自动注入
 *
 * 依赖注入 那么这个依赖 的 来源是是那些 或者说 bean的来源有那些
 * bean  自定义的bean  容器内建的bean
 * 非bean    容器内建的依赖
 *
 *
 * beanFactory applicationContext关系  没看懂。。。
 */
public class DependencyInjection {
    public static void main(String[] args) {
        // 配置 XML 配置文件
        // 启动 Spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-injection-context.xml");
        UserRepository userRepository0 = beanFactory.getBean("userRepository", UserRepository.class);
        System.out.println("通过类型自动注入："+userRepository0.getUsers());



        // 依赖来源一：自定义 Bean
        UserRepository userRepository = beanFactory.getBean("userRepository", UserRepository.class);
        System.out.println("自定义的bean：" + userRepository.getUsers());
        // 依赖来源二：容器內建 Bean
        Environment environment = beanFactory.getBean(Environment.class);
        System.out.println("容器内建的bean：" + environment);

        // 依赖查找（错误）
//        System.out.println(beanFactory.getBean(BeanFactory.class));
        System.out.println(userRepository.getBeanFactory() == beanFactory);
        // 依赖来源三：依赖注入（內建依赖）
        System.out.println("容器内建的依赖：" + userRepository.getBeanFactory());


//        beanFactory applicationContext关系  没看懂。。。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-injection-context.xml");
        UserRepository userRepository1 = applicationContext.getBean("userRepository", UserRepository.class);
        whoIsIoCContainer(userRepository1, applicationContext);


        ObjectFactory userFactory = userRepository1.getObjectFactory();
        System.out.println(userFactory.getObject() == applicationContext);




    }

    private static void whoIsIoCContainer(UserRepository userRepository, ApplicationContext applicationContext) {


        // ConfigurableApplicationContext <- ApplicationContext <- BeanFactory

        // ConfigurableApplicationContext#getBeanFactory()

        // 这个表达式为什么不会成立
        System.out.println(userRepository.getBeanFactory() == applicationContext);
        System.out.println(userRepository.getBeanFactory() == applicationContext.getParentBeanFactory());

        // ApplicationContext is BeanFactory

    }

}
